package com.cgsd.heyu.ui.webview;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.android.library.utils.StringUtils;
import com.android.library.utils.ToastHelper;
import com.apkfuns.logutils.LogUtils;
import com.cgsd.heyu.R;
import com.cgsd.heyu.presenter.BasePresenter;
import com.cgsd.heyu.ui.BaseActivity;
import com.cgsd.heyu.utils.ImagePreviewActivity;

;import java.io.File;
import java.util.ArrayList;

/**
 * @author xiaoxing
 * 支持图片上传
 */
public class CommonH5SupportImgActivity extends BaseActivity<BasePresenter> {

    private static final int FILECHOOSER_RESULTCODE = 10000;
    private static final int FILECHOOSER_RESULTCODE_FOR_ANDROID_5 = 10005;

    private WebView mWebView;
    private String url;
    /**
     * 标题自定义
     */
    private boolean isOnPause;
    private String customTitle;

    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> mUploadMessageForAndroid5;

    public static void actionStart(Activity activity, String url, String title) {
        if (StringUtils.isEmpty(url)) {
            return;
        }
        LogUtils.e("url = "+url);
        Intent intent = new Intent(activity, CommonH5SupportImgActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("title", title);
        activity.startActivity(intent);

    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_common_webview;
    }

    @SuppressLint({"SetJavaScriptEnabled", "JavascriptInterface"})
    @Override
    protected void initView() {
        url = getIntent().getStringExtra("url");
        customTitle = getIntent().getStringExtra("title");
        mWebView = findViewById(R.id.mWebView);

        WebSettings webSettings = mWebView.getSettings();
        //是否开启JS支持
        webSettings.setJavaScriptEnabled(true);
        //是否允许JS打开新窗口
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        //缩放至屏幕大小
        webSettings.setUseWideViewPort(true);
        //缩放至屏幕大小
        webSettings.setLoadWithOverviewMode(true);
        //是否支持缩放
        webSettings.setSupportZoom(true);
        //是否支持缩放变焦，前提是支持缩放
        webSettings.setBuiltInZoomControls(true);
        //是否隐藏缩放控件
        webSettings.setDisplayZoomControls(false);
        //是否允许访问文件
        webSettings.setAllowFileAccess(true);
        //是否节点缓存
        webSettings.setDomStorageEnabled(true);
        //是否数据缓存
        webSettings.setDatabaseEnabled(true);
        //是否要手势触发媒体
        webSettings.setMediaPlaybackRequiresUserGesture(false);
        //是否自动加载图片
        webSettings.setLoadsImagesAutomatically(true);
        //设置编码格式
        webSettings.setDefaultTextEncodingName("UTF-8");
        //是否需要获取焦点
        webSettings.setNeedInitialFocus(true);
        //是否从网络获取资源
        webSettings.setBlockNetworkLoads(false);
        //WebView默认不支持同时加载Https和Http混合模式。
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);


        mWebView.addJavascriptInterface(new webImgInterface(), "imagelistner");

        mWebView.setBackgroundColor(0);
        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                //不拦截url
                return false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                //js 注入
                addImageClickListener();
                dismissCommonSubmitDialog();
            }
        });

        mWebView.setWebChromeClient(new MyWebChromeClient());
    }

    // 注入js函数监听
    private void addImageClickListener() {
        mWebView.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName(\"img\"); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{"
                + "    objs[i].onclick=function()  " +
                "    {  "
                + "        window.imagelistner.openImage(this.src);  " +
                "    }  " +
                "}" +
                "})()");
    }

    // js 通信接口
    public class webImgInterface {

        @JavascriptInterface
        public void openImage(String img) {
            LogUtils.e("JavascriptInterface = " + img);
            ArrayList<String> list = new ArrayList<>();
            list.add(img);
            startActivity(ImagePreviewActivity.getIntent(CommonH5SupportImgActivity.this, list, 0));
        }
    }

    private class MyWebChromeClient extends WebChromeClient {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (StringUtils.isNotEmpty(customTitle)) {
                mTitleBar.setTitle(customTitle);
            } else {
                mTitleBar.setTitle(title);
            }
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {

            super.onProgressChanged(view, newProgress);
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg) {

            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            startActivityForResult(
                    Intent.createChooser(i, "File Chooser"),
                    FILECHOOSER_RESULTCODE);

        }

        public void openFileChooser(ValueCallback uploadMsg,
                                    String acceptType) {
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            startActivityForResult(
                    Intent.createChooser(i, "File Browser"),
                    FILECHOOSER_RESULTCODE);
        }

        // For Android 4.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                    String acceptType, String capture) {
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            startActivityForResult(
                    Intent.createChooser(i, "File Chooser"),
                    FILECHOOSER_RESULTCODE);

        }

        @Override
        public boolean onShowFileChooser(WebView webView,
                                         ValueCallback<Uri[]> filePathCallback,
                                         FileChooserParams fileChooserParams) {
            openFileChooserImplForAndroid5(filePathCallback);
            return true;//重要，没有这个会报错
        }
    }

    //选择图片
    private void openFileChooserImplForAndroid5(ValueCallback<Uri[]> uploadMsg) {
        mUploadMessageForAndroid5 = uploadMsg;
        Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
        contentSelectionIntent.setType("image/*");
        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
        chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
        startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE_FOR_ANDROID_5);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage)
                return;
            Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
            if (result == null) {
                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;
                return;
            }

            //外界的程序访问ContentProvider所提供数据 可以通过ContentResolver接口
            ContentResolver resolver = getContentResolver();
            try {
                Uri originalUri = intent.getData(); // 获得图片的uri
                // 获取图片的路径：
                String[] proj = {MediaStore.Images.Media.DATA};
                // 好像是android多媒体数据库的封装接口，具体的看Android文档
                Cursor cursor = managedQuery(originalUri, proj, null, null, null);
                //  这个是获得用户选择的图片的索引值
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                // 将光标移至开头 ，这个很重要，不小心很容易引起越界
                cursor.moveToFirst();
                // 最后根据索引值获取图片路径
                String path = cursor.getString(column_index);
                Uri uri = Uri.fromFile(new File(path));
                mUploadMessage.onReceiveValue(uri);
            } catch (Exception e) {
                Log.e("TAG-->Error", e.toString());
            }
        } else if (requestCode == FILECHOOSER_RESULTCODE_FOR_ANDROID_5) {
            if (null == mUploadMessageForAndroid5)
                return;
            Uri result = (intent == null || resultCode != RESULT_OK) ? null : intent.getData();
            if (result != null) {
                mUploadMessageForAndroid5.onReceiveValue(new Uri[]{result});
            } else {
                mUploadMessageForAndroid5.onReceiveValue(new Uri[]{});
            }
            mUploadMessageForAndroid5 = null;
        }
    }

    @Override
    protected void clickLeft() {
        setResult(RESULT_OK);
        finish();
    }

    @Override
    protected void onPause() {
        super.onPause();
        try {
            if (mWebView != null) {
                mWebView.getClass().getMethod("onPause").invoke(mWebView, (Object[]) null);
                isOnPause = true;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            if (isOnPause) {
                if (mWebView != null) {
                    mWebView.getClass().getMethod("onResume").invoke(mWebView, (Object[]) null);
                }
                isOnPause = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mWebView.setWebChromeClient(null);
        mWebView.setWebViewClient(null);
        mWebView.getSettings().setJavaScriptEnabled(false);
        mWebView.clearCache(true);

        mWebView.reload();
        mWebView.removeAllViews();
        mWebView.destroy();
        finish();

    }

    @Override
    public void initData() {
        mWebView.loadUrl(url);
    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            setResult(RESULT_OK);
            finish();
        }
    }
}
